<?php

namespace App\Http\Controllers;

use App\Http\Requests\AttendanceCreate;
use App\Http\Requests\StudentCreate;
use App\Http\Requests\StudentUpdate;
use App\Models\Attendance;
use App\Models\Card;
use App\Models\Course;
use App\Models\Student;
use App\Models\StudentCard;
use App\Models\Subject;
use App\Services\CourseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller
{
    public function list(Request $request)
    {
        $limit = $request->limit ?? 10;

        $res = Student::with(['studentCard', 'studentCard.card', 'class:id,class_name'])->where([
            'school_id' => $request->school_id,
            'campus_id' => $request->campus_id
        ])->paginate($limit);

        $res->each(function($item){

            if($item->class){
                $item->class->each(function($class){
                    $class->makeHidden('pivot');
                });
            }

            if($item->studentCard){
                $item->studentCard->each(function($studentCard){
                    $studentCard['card_name'] = $studentCard->card['card_name'];
                    $studentCard['card_type'] = $studentCard->card['card_type'];
                    $studentCard->makeHidden('card');
                });
            }
        });

        return resSucc(formatPage($res), "学生列表");
    }

    // 创建学生
    public function create(StudentCreate $request)
    {

        $student = $request->validated();
        $student['school_id'] = $request->school_id;
        $student['campus_id'] = $request->campus_id;

        try {
            $res = Student::create($student);
            return resSucc($res, "创建成功");
        } catch (\Exception $e) {
            return resFail($e, "创建失败");
        } catch (\Throwable $e) {
            return resFail($e, "创建失败");
        }
    }

    public function update(StudentUpdate $request)
    {

        $student = $request->validated();
        $id = $student['student_id'];
        unset($student['student_id']);
        try {
            $res = Student::where('id', $id)->update($student);
            return resSucc($res, "更新成功");
        } catch (\Exception $e) {
            return resFail($e, "更新失败");
        } catch (\Throwable $e) {
            return resFail($e, "更新失败");
        }
    }

    public function info(Request $request, $id)
    {
        $school_id =  $request->school_id;
        $campus_id = $request->campus_id;
        $res = Student::where([
            'school_id' => $school_id,
            'campus_id' => $campus_id,
            'id' => $id,
        ])->first();
        return resSucc($res, "学生详情");
    }

    public function course(Request $request)
    {

        $res = CourseService::StudentCourselist($request);

        return resSucc(formatPage($res), "课表");
    }

    // 考勤
    public function attendance(AttendanceCreate $request)
    {

        $course_id = $request->course_id;
        $card_id = $request->card_id;
        $deduct = $request->deduct;
        $student_id = $request->student_id;
        $school_id = $request->school_id;
        $campus_id = $request->campus_id;
        $status = $request->status;

        // 1. 先在考勤记录表中查询 是否有考勤记录
        $attendance = Attendance::where([
            'student_id' => $student_id,
            'course_id' => $course_id
        ])->first();

        DB::beginTransaction();

        try {

            // 2. 考勤存在，修改
            if ($attendance) {

                // a. 修改考勤，先加上 上次减去的，再判断当前是否需要扣除
                StudentCard::where('id', $card_id)->increment('residue', $attendance->last_kx);

                if ($deduct == 1) {
                    StudentCard::where('id', $card_id)->decrement('residue', $attendance->kx);
                    $attendance->last_kx = $attendance->kx;
                } else {
                    $attendance->last_kx = 0;
                }

                $attendance->status = $status;
                $attendance->operator_id = Auth::id() ?? 0;
                $attendance->save();

                DB::commit();

                return resSucc(null, "考勤成功");

            } else {

                // 2. 考勤不存在，创建
                $kx = 0;
                $last_kx = 0;

                $card_type_id = StudentCard::where('id', $course_id)->value('card_type_id');

                if(!$card_type_id){
                    return resSucc(null, "学员卡不存在");
                }

                $cardType = Card::where('id', $card_type_id)->value('card_type');

                if(!$card_type_id){
                    return resSucc(null, "学员卡不存在");
                }

                $subject_id = Course::where('id', $course_id)->value('subject_id');

                if(!$subject_id){
                    return resSucc(null, "课程不存在");
                }

                $subject_price = Subject::where('id', $subject_id)->first(['ks_value', 'cz_value']);

                if ($cardType == 1) {
                    $kx = $subject_price->ks_value ?? 0;
                }

                if ($cardType == 2) {
                    $kx = $subject_price->cz_value ?? 0;
                }

                $last_kx = $deduct == 1 ? $kx : 0;

                $attendance = new Attendance;
                $attendance->school_id = $school_id;
                $attendance->campus_id = $campus_id;
                $attendance->student_id = $student_id;
                $attendance->course_id = $course_id;
                $attendance->status = $status;
                $attendance->card_id = $card_id;
                $attendance->kx = $kx;
                $attendance->last_kx = $last_kx;
                $attendance->operator_id = Auth::id() ?? 0;
                $attendance->save();

                // 扣除学员卡 余额
                StudentCard::where('id', $card_id)->decrement('residue', $last_kx);

                DB::commit();

                return resSucc(null, "考勤成功");
            }
        } catch (\Exception $e) {
            DB::rollback();
            return resFail($e, "考勤失败");
        } catch (\Throwable $e) {
            DB::rollback();
            return resFail($e, "考勤失败");
        }
    }

    // 考勤记录
    public function AttendanceList(Request $request){

        $school_id = $request->school_id;
        $campus_id = $request->campus_id;
        $student_id = $request->student_id;
        $limit = $request->limit ?? 10;

        $res = Attendance::with([
            'course:id,subject_id',
            'course.subject:id,subject_name',
            'studentCard',
            'studentCard.card:id,card_name'
        ])->where([
            'school_id' => $school_id,
            'campus_id' => $campus_id,
            'student_id' => $student_id
        ])->paginate($limit);

        foreach ($res as $item) {

            $item->append('subject_name');
            $item->makeHidden('course');

            $item->studentCard->append('card_name');
            $item->studentCard->makeHidden('card');

        }

        return resSucc(formatPage($res), '学员考勤列表');
    }
}
